
const Service = require('egg').Service
const md5 = require('md5')

class AuthService extends Service {
  // 登录
  async login(params) {
    const { ctx, app } = this
    const { username, password } = params
    const data = await ctx.find('User', {
      attributes: ['id', 'username', 'nickname', 'headIcon', 'phone', 'email', 'identify', 'signature'],
      where: {
        username,
        password: md5(password + app.config.salt)
      }
    })
    if (!data) {
      ctx.renderBack(null, '0', '账号或密码输入不正确')
      return
    }
    const { id, nickname, headIcon, identify, phone, email, signature } = data.dataValues
    // token生成
    const token = await ctx.helper.generateToken({ id })
    if (token) {
      const res = {
        userInfo: {
          id,
          username,
          nickname,
          headIcon,
          phone,
          signature,
          email,
          identify: [identify]
        },
        ...token
      }
      return res
    }
  }

  // 注册
  async register(params) {
    const { ctx, app } = this
    const { username, password, phone, nickname, email } = params
    const hasUser = await ctx.find('User', {
      where: {
        username
      }
    })
    if (hasUser) {
      return -1
    }
    const hasEmail = await ctx.find('User', {
      where: {
        email
      }
    })
    if (hasEmail) {
      return -2
    }
    const res = await ctx.create('User', {
      username,
      phone,
      nickname,
      email,
      identify: 'user',
      status: 1,
      type: 1,
      password: md5(password + app.config.salt)
    })
    return res
  }

  // token 刷新
  async refreshToken(token) {
    const { ctx, app } = this
    try {
      const decode = await app.jwt.verify(token, app.config.jwt.secret)
      if (decode) {
        const token = await ctx.helper.generateToken({ id: decode.id })
        if (token) { return token }
      }
    } catch (err) {
      if (err.name === 'JsonWebTokenError') {
      // ctx.throw(401, '[Unauthorized] Token 令牌不合法!')
        ctx.throw(401, '[Unauthorized] ' + err.message)
      } else if (err.name === 'TokenExpiredError') {
        ctx.throw(401, '[Token Expired] 权限过期')
      }
    }
  }
}

module.exports = AuthService
